<template>
    <view>
        <view>
            <view class="top">
                <view class="search">
                    <view class="search_in" @click="goSearch()">
                        <image src="../../static/image/camera.png"></image>
                        <input type="text" placeholder="请输入搜素内容"/>
                        <view class="search_btn">搜索</view>
                    </view>
                </view>
            </view>
        </view>
        <!--药材分类列表-->
        <view style="margin: 10rpx 0">
            <view style="background-color: #ffffff; display: flex; border-radius: 10rpx;overflow: hidden;margin-bottom: 10rpx;text-align: center;">
                <view style="padding: 20rpx;font-size: 48rpx;color: black;" :class="{ 'active': current === type }" @click="selectType(type)" v-for="type in types" :key="type">{{type}}</view>
            </view>
        </view>

        <!--分类药材展示-->
        <view style="display: flex;background-color: #e9f1d8;border-radius: 10rpx;padding: 10rpx 0;">
            <view style="width: 160rpx; text-align: center;">
                <view v-for="item in sortList" :key="item.id" class="property-item" :class="{ 'property-active': item.id === sortactiveid }" @click="selectProperty(item)">{{ getPropertyText(item) }}</view>
            </view>
            <!--药材图片显示-->
            <scroll-view scroll-y="true" style="height: 95vh;">
                <view class="content">
                    <view v-for="item in filterList" :key="item.id" class="classlist" @click="goToDetail(item.id)">
                        <image :src="item.icon" style="width: 200rpx; height: 200rpx; border-radius: 10rpx; display: block;"></image>
                        <text style="color: black;font-size: 35rpx;">{{item.mname}}</text>
                    </view>
                </view>
                <!--无药材时显示文本-->
                <view v-if="filterList.length === 0" style="text-align: center; margin-top: 20rpx;font-size: 32rpx;">暂无药材数据,敬请期待</view>
            </scroll-view>
        </view>
        <!--展示列表结束-->
    </view>
</template>

<script>
    export default {
        data() {
            return {
              sortList: [],
              sortactiveid: 0,
              medicineList: [],
              filterList: [],
              current: '药性',
              types: ['药性', '归经', '味'],
              defaultFilters: {
                '药性': '大寒',
                '归经': '膀胱经',
                '味': '微甘'
                }
            };
        },
        onLoad() {
            this.load();
            this.loadProperty();
            this.setDefaultFilter();
        },
        methods: {
            goSearch() {
                uni.navigateTo({
                    url: '/pages/search/search'
                })
            },
            goToDetail(id) {
                uni.navigateTo({
                    url: '/pages/detail/detail?id=' + id,
                });
            },
            async selectType(type) {
                this.current = type;
                await this.load(type);
                // 当切换到归经类型时，手动触发一次根据默认值的筛选
                if (this.current === '归经') {
                    this.selectProperty({ mjing: this.defaultFilters['归经'] });
                }else if(this.current ==='味'){
                  this.selectProperty({mflavor:this.defaultFilters['味']});
                }
                this.setDefaultFilter();
            },
           selectProperty(item = this.sortList[0]) {
               this.sortactiveid = item.id;
               const propertyKey = this.getPropertyKey(this.current);
               if (this.current === '归经') {
                   this.filterList = this.medicineList.filter((med) => {
                       const medMjingValue = med[propertyKey];
                       if (medMjingValue!== undefined) {
                          const medMjingValues = medMjingValue.split('、');
                          return medMjingValues.includes(item[propertyKey]);
                       }
                       return false;
                   });
               } else if (this.current === '味') {
                   this.filterList = this.medicineList.filter((med) => {
                       const medMflavorValue = med[propertyKey];
                       if (medMflavorValue!== undefined) {
                           const medMflavorValues = medMflavorValue.split('、');
                           return medMflavorValues.includes(item[propertyKey]);
                       }
                       return false;
                   });
               } else {
                   this.filterList = this.medicineList.filter((med) => med[propertyKey] === item[propertyKey]);
               }
           },
            getPropertyKey(type) {
              const keys = { '药性': 'mproperty', '归经': 'mjing', '味': 'mflavor' };
              return keys[type];
            },
            getPropertyText(item) {
                const keys = { '药性': 'mproperty', '归经': 'mjing', '味': 'mflavor' };
                return item[keys[this.current]];
            },
            load(type) {
                if (type === '归经') {
                    this.$request.get('/d_guijing/selectAll').then(res => {
                      this.sortList = res.data || [];
                      // 处理归经数据可能包含多个值的情况，将其拆分成单独条目
                      this.sortList = this.sortList.map((entry) => {
                      const mjingValues = entry.mjing.split('、');
                      return mjingValues.map((value) => ({...entry, mjing: value }));
                    }).flat();
                    if (this.sortList.length > 0) {
                    this.sortactiveid = this.sortList[0].id
                    }
                    // 获取归经数据完成后，立即根据默认的膀胱经进行筛选
                    this.filterList = this.medicineList.filter((med) => {
                    const medMjingValues = med['mjing'].split('、');
                    return medMjingValues.includes(this.defaultFilters['归经']);                         });
                })
                } else if (type === '味') {
                    this.$request.get('/d_flavor/selectAll').then(res => {
                      this.sortList = res.data || [];
                      //多个味
                      this.sortList = this.sortList.map((entry) =>{
                        const mflavorValue = entry.mflavor;
                        if (mflavorValue!== undefined) {
                        const mflavorValues = mflavorValue.split('、');
                        return mflavorValues.map((value) => ({...entry, mflavor: value }));
                        }
                        return entry;
                        }).flat();
                        if (this.sortList.length > 0) {
                            this.sortactiveid = this.sortList[0].id
                        }
                       this.filterList = this.medicineList.filter((med) => {
                         const medMflavorValue = med['mflavor'];
                         if (medMflavorValue!== undefined) {
                           const medMflavorValues = medMflavorValue.split('、');
                           return medMflavorValues.includes(this.defaultFilters['味']);
                           }
                           return false;  
                        });
                    })
                } else {
                    this.$request.get('/d_property/selectAll').then(res => {
                        this.sortList = res.data || [];

                        if (this.sortList.length > 0) {
                            this.sortactiveid = this.sortList[0].id
                        }
                    })
                }
            },
            loadProperty() {
                this.$request.get('/medicines/selectAll')
                   .then(res => {
                        if (res && res.data) {
                            this.medicineList = res.data;
                            //默认
                            this.setDefaultFilter();
                        } else {
                            console.error('No data received or data is not in expected format');
                        }
                    })
                   .catch(error => {
                        console.error('Error fetching data:', error);
                    });
            },
            setDefaultFilter() {
                const defaultFilter = this.defaultFilters[this.current];
                this.filterList = this.medicineList.filter(item => {
                    const propertyKey = this.getPropertyKey(this.current);
                    return item[propertyKey] === defaultFilter;
                });
            }
        
        },
    }
</script>

<style>
 .search {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100rpx;
        background-color: #a1cc97;
    }

 .search_in {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20rpx;
        box-sizing: border-box;
        height: 70rpx;
        width: 730rpx;
        background-color: #ffffff;
        border-radius: 35rpx;
    }

    image {
        height: 45rpx;
        width: 45rpx;
    }

 .search_btn {
        height: 55rpx;
        width: 110rpx;
        border-radius: 55rpx;
        background-color: #a1cc97;
        color: #ffffff;
        text-align: center;
        line-height: 55rpx;
        cursor: pointer;
    }

    input {
        width: 480rpx;
    }

 .content {
        width: 590rpx;
        display: flex;
        flex-wrap: wrap;
        justify-content: start;
        align-items: flex-start;
    }

 .classlist {
        background-color: #fff;
        width: 260rpx;
        height: 270rpx;
        margin-left: 30rpx;
        margin-bottom: 30rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

 .box {
        background-color: #fff;
        border-radius: 10rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0,.2);
        height: 70rpx;
    }

 .property-active {
        background-color: #e9f1d8!important;
        border-left: 5rpx solid #8baf82;
        color: #008000!important;
    }

 .property-item {
        height: 60rpx;
        padding: 15rpx;
        background-color: #8baf82;
        color: #fff;
    }

 .catelist {
        display: flex;
        flex-wrap: wrap;
        width: 615rpx;
    }

 .cateitem {
        width: 32.5%;
        height: 100rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border: 1rpx solid;
        background-color: #000000;
        animation-delay: 0s;
        animation-fill-mode: both;
        animation-iteration-count: infinite;
    }

    text {
        font-size: 32rpx;
    }

 .active {
        background-color: #a1cc97
    }
</style>